using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DealerPlatform.Web.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;

namespace DealerPlatform.Extensions
{
    public static class AuthenticationExtensions
    {
        /// <summary>
        /// 设置鉴权
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <param name="IsDevelopment"></param>
        /// <returns></returns>
        public static IServiceCollection MyAddAuthentication(this IServiceCollection services, IConfiguration configuration, bool IsDevelopment)
        {
            var token = configuration.GetSection("Jwt").Get<JwtTokenModel>();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(opt =>
            {
                opt.RequireHttpsMetadata = !IsDevelopment;  //是否是Https，默认true
                opt.SaveToken = true;
                opt.TokenValidationParameters = new()
                {
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(token.Security)),
                    ValidIssuer = token.Issuer,
                    ValidAudience = token.Audience,
                };
                opt.Events = new JwtBearerEvents
                {
                    OnChallenge = context =>
                    {
                        //此处终止代码
                        context.HandleResponse();
                        var res = "{\"code\":\"401\",\"err\":\"无权限\"}";
                        context.Response.ContentType = "application/json";
                        context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                        context.Response.WriteAsync(res);
                        return Task.FromResult(0);
                    }
                };
            });
            return services;
        }

        /// <summary>
        /// 在Swagger中使用鉴权
        /// </summary>
        /// <param name="services"></param>
        /// <param name="title"></param>
        /// <param name="version"></param>
        /// <returns></returns>
        public static IServiceCollection MyAddSwaggerGen(this IServiceCollection services, string title, string version = "v1")
        {
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc(version, new OpenApiInfo { Title = title, Version = version });
                //添加安全定义
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "格式：Bearer {token}",
                    Name = "Authorization",         //默认的参数名
                    In = ParameterLocation.Header,  //放于请求头中
                    Type = SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });
                //添加安全要求
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference=new OpenApiReference{
                                Type = ReferenceType.SecurityScheme,
                                Id="Bearer"
                            }
                        }, new string[]{}
                    }
                });
            });
            return services;
        }
    }
}